package com.hzjh.base.ext.utils

import android.content.Context
import android.net.Uri
import com.hzjh.base.ext.widget.dialog.SelectGetPictureModeDialog
import com.hzjh.base.frame.activity.AbsActivity
import com.hzjh.base.log.JHLogger
import com.hzjh.base.utils.other.ActivityStackManage
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.DateUtils
import com.luck.picture.lib.utils.MediaUtils
import com.luck.picture.lib.utils.PictureFileUtils
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import java.io.File

class ImageSelectUtils {
    val activity =ActivityStackManage.currentActivity() as AbsActivity
    private var jhImageUpViewI: ((String) -> Unit)? = null

    fun showSelectImgDialog(jhImageUpViewI: (String) -> Unit){
        this.jhImageUpViewI = jhImageUpViewI
        SelectGetPictureModeDialog()
            .setSelectResult{
                if (it == SelectGetPictureModeDialog.GET_PICTURE_MODE_TAKE_PICTURE) {
                    getPictureByTakePhoto()
                } else {
                    getPictureBySystemGallery()
                }
            }
            .show(activity.supportFragmentManager, SelectGetPictureModeDialog::class.simpleName)
    }

    // 使用系统相机拍照
    private fun getPictureByTakePhoto() {
        PictureSelector.create(activity)
            .openCamera(SelectMimeType.ofImage())
            .setCompressEngine(ImageFileCompressEngine()) //压缩图片
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>) {
                    analyticalSelectResults(result)
                    if (result.isNotEmpty()) {
                        JHLogger.d("TakePhoto=${result[0].availablePath}")
                        handleSelectedPicture(result[0].availablePath)
                    }
                }

                override fun onCancel() {
                    JHLogger.d( "PictureSelector Cancel")
                }
            })
    }

    // 从系统相册选择
    private fun getPictureBySystemGallery() {
        PictureSelector.create(activity)
            .openSystemGallery(SelectMimeType.ofImage()) //从系统相册选图
            .setSelectionMode(SelectModeConfig.SINGLE) //单选
            .setCompressEngine(ImageFileCompressEngine()) //压缩图片
            .setSkipCropMimeType(PictureMimeType.ofGIF(), PictureMimeType.ofWEBP()) //跳过不需要裁剪的类型
//                .setCustomLoadingListener(getCustomLoadingListener())
            .forSystemResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>) {
                    analyticalSelectResults(result)
                    if (!result.isEmpty()) {
                        handleSelectedPicture(result[0].availablePath)
                    }
                }

                override fun onCancel() {
                    JHLogger.d("PictureSelector Cancel")
                }
            })
    }
    /**
     * 处理已选择的图片
     */
    fun handleSelectedPicture(image: String) {
        JHLogger.d("onImageSelect=$image")
        jhImageUpViewI?.invoke(image)
    }

    /**
     * 处理选择结果
     *
     * @param result
     */
    private fun analyticalSelectResults(result: ArrayList<LocalMedia>) {
        if (result == null) return
        for (media in result) {
            if (media.width == 0 || media.height == 0) {
                if (PictureMimeType.isHasImage(media.mimeType)) {
                    val imageExtraInfo = MediaUtils.getImageSize(activity, media.path)
                    media.width = imageExtraInfo.width
                    media.height = imageExtraInfo.height
                } else if (PictureMimeType.isHasVideo(media.mimeType)) {
                    val videoExtraInfo = MediaUtils.getVideoSize(activity, media.path)
                    media.width = videoExtraInfo.width
                    media.height = videoExtraInfo.height
                }
            }
            JHLogger.d("文件名: " + media.fileName)
            JHLogger.d("是否压缩:" + media.isCompressed)
            JHLogger.d("压缩:" + media.compressPath)
            JHLogger.d("初始路径:" + media.path)
            JHLogger.d("绝对路径:" + media.realPath)
            JHLogger.d("是否裁剪:" + media.isCut)
            JHLogger.d("裁剪路径:" + media.cutPath)
            JHLogger.d("是否开启原图:" + media.isOriginal)
            JHLogger.d("原图路径:" + media.originalPath)
            JHLogger.d("沙盒路径:" + media.sandboxPath)
            JHLogger.d("水印路径:" + media.watermarkPath)
            JHLogger.d("视频缩略图:" + media.videoThumbnailPath)
            JHLogger.d("原始宽高: " + media.width + "x" + media.height)
            JHLogger.d("裁剪宽高: " + media.cropImageWidth + "x" + media.cropImageHeight)
            JHLogger.d(
                "文件大小: " + PictureFileUtils.formatAccurateUnitFileSize(media.size)
            )
            JHLogger.d("文件时长: " + media.duration)
        }
    }

    /**
     * 自定义压缩
     */
    private class ImageFileCompressEngine : CompressFileEngine {
        override fun onStartCompress(
            context: Context,
            source: java.util.ArrayList<Uri>,
            call: OnKeyValueResultCallbackListener
        ) {
            Luban.with(context).load(source)
                .setRenameListener { filePath ->
                    // 设置压缩后的文件名
                    val indexOf = filePath.lastIndexOf(".")
                    val postfix = if (indexOf != -1) filePath.substring(indexOf) else ".jpg"
                    DateUtils.getCreateFileName("CMP_") + postfix
                }.filter { path ->
                    // 仅压缩图片，Gif跳过
                    if (PictureMimeType.isUrlHasImage(path) && !PictureMimeType.isHasHttp(path)) {
                        true
                    } else {
                        !PictureMimeType.isUrlHasGif(path)
                    }
                }.setCompressListener(object : OnNewCompressListener {
                    override fun onStart() {}
                    override fun onSuccess(source: String, compressFile: File) {
                        if (call != null) {
                            call.onCallback(source, compressFile.absolutePath)
                        }
                    }

                    override fun onError(source: String, e: Throwable?) {
                        if (call != null) {
                            call.onCallback(source, null)
                        }
                    }
                }).launch()
        }
    }
}